﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Main_Data;
using System.IO;
using DevExpress.XtraReports.UI;
using System.Collections;
namespace Print_UI
{
    public partial class FrmCreateTemplateUser : CommonForm
    {
        public FrmCreateTemplateUser()
        {
            InitializeComponent();
        }
        public byte[] TemplateStream { get; set; }
        public bool IsChanged { get; set; }
        private CommandParams _cmd = new CommandParams();
        private int _id = -1;
        private dsReport _ds;

        private void LoadAuth()
        {
            if (Actions != null)
            {
                if (Actions.Contains("Add"))
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                else
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                if (Actions.Contains("Edit"))
                {
                    btnCopy.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    AcceptButton = btnSave;
                }
                else
                {
                    btnCopy.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

            }
        }
        private void CheckAuth(string key)
        {
            if (Actions != null && Actions.Contains(key))
            {
                if (key == "Add")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                if (key == "Edit")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            {
                try
                {
                    if (CheckInput())
                    {
                        var template = Model.PRI_Template.FirstOrDefault(c => c.ID == _id);
                        object obj = gridView3.GetFocusedRowCellValue("ID");
                        if (template != null)
                        {
                            int id = Convert.ToInt32(obj);

                            if (obj != null)
                            {
                                FrmCreateTemplate frm = new FrmCreateTemplate();
                                frm.Data = _ds;
                                frm.TemplateStream = template.Stream;
                                frm.ShowDialog();
                                template.ModifiedDate = DateTime.Now;
                                template.ModifiedBy = UserName;
                                template.TemplateName = txtTemp.EditValue.ToString();
                                template.IsPublic = false;
                                if (frm.IsChanged)
                                {
                                    template.Stream = frm.TemplateStream;

                                }

                            }
                        }
                        else
                        {

                            template = new Main_Data.PRI_Template();
                            template.ID = -1;
                            template.CreatedDate = DateTime.Now;
                            template.CreatedBy = UserName;
                            template.DepartmentID = DepartmentID;
                            template.TemplateName = txtTemp.EditValue.ToString();
                            FrmCreateTemplate frm = new FrmCreateTemplate();
                            frm.Data = _ds;
                            frm.TemplateStream = template.Stream;
                            frm.ShowDialog();
                            template.YearID = Convert.ToInt32(cboYear.EditValue);
                            template.SemesterID = Convert.ToInt32(cboSemester.EditValue);
                            template.IsPublic = false;
                            if (_id == -1)
                                Model.AddToPRI_Template(template);
                            if (frm.IsChanged)
                            {
                                template.Stream = frm.TemplateStream;

                            }

                        }
                        CommonMessage("Cập nhật thành công");
                        Model.SaveChanges();
                        LoadData();
                        txtTemp.Text = string.Empty;
                        cboSemester.EditValue = -1;
                        cboYear.EditValue = -1;
                    }
                     
                }


                catch (Exception ex)
                {
                    CommonError(ex);
                }
            }
        }

        private bool CheckInput()
        {
            bool result = true;
            dxErrorProvider1.ClearErrors();
            if (int.Parse(cboSemester.EditValue.ToString()) == -1 && int.Parse(cboYear.EditValue.ToString()) == -1 && txtTemp.Text == string.Empty)
            {
                dxErrorProvider1.SetError(cboYear, "Chưa Chọn Giá Trị");
                dxErrorProvider1.SetError(cboSemester, "Chưa Chọn Giá Trị");
                dxErrorProvider1.SetError(txtTemp, "Chưa Nhập Giá Trị");
                result = false;
            }
            else
            {
                if (txtTemp.Text == string.Empty)
                {
                    dxErrorProvider1.SetError(txtTemp, "Chưa Nhập Giá Trị");
                    result = false;
                }
                if (int.Parse(cboSemester.EditValue.ToString()) == -1)
                {
                    dxErrorProvider1.SetError(cboSemester, "Chưa Chọn Giá Trị");
                    result = false;
                }
                if (int.Parse(cboYear.EditValue.ToString()) == -1)
                {
                    dxErrorProvider1.SetError(cboYear, "Chưa Chọn Giá Trị");
                    result = false;
                }

                
            }
            return result;
        }

        private void LoadSchoolYear()
        {

            var Year = (from p in Model.CAT_Year
                        join k in Model.PRI_SemesterSetting on p.ID equals k.YearID
                        select new { p.ID, p.Name }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "----Chọn Năm Học----");
            foreach (var item in Year)
            {
                dic.Add(item.ID, item.Name);
            }

            cboYear.Properties.ValueMember = "Key";
            cboYear.Properties.DisplayMember = "Value";
            cboYear.Properties.DataSource = dic;
            cboYear.EditValue = -1;
        }
        //Load Semester
        private void LoadSemester()
        {

            Dictionary<int, string> dic = new Dictionary<int, string>();
            int iYear = Convert.ToInt32(cboYear.EditValue);
            var Semester = from obj in Model.PRI_SemesterSetting
                           where (obj.YearID == iYear)
                           select new
                           {
                               obj.CAT_Semester.ID,
                               obj.CAT_Semester.SemesterName
                           };
            dic.Add(-1, "----Chọn Học Kì----");
            foreach (var item in Semester)
            {
                dic.Add(item.ID, item.SemesterName);

            }
            cboSemester.Properties.ValueMember = "Key";
            cboSemester.Properties.DisplayMember = "Value";
            cboSemester.Properties.DataSource = dic;
            cboSemester.EditValue = -1;

        }
        private void LoadSchoolYear1()
        {

            var Year = (from p in Model.CAT_Year
                        join k in Model.PRI_SemesterSetting on p.ID equals k.YearID
                        select new { p.ID, p.Name }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "----Chọn Năm Học----");
            foreach (var item in Year)
            {
                dic.Add(item.ID, item.Name);
            }

            cboyear1.Properties.ValueMember = "Key";
            cboyear1.Properties.DisplayMember = "Value";
            cboyear1.Properties.DataSource = dic;
            cboyear1.EditValue = -1;
        }
        //Load Semester
        private void LoadSemester1()
        {

            Dictionary<int, string> dic = new Dictionary<int, string>();
            int iYear = Convert.ToInt32(cboyear1.EditValue);
            var Semester = from obj in Model.PRI_SemesterSetting
                           where (obj.YearID == iYear)
                           select new
                           {
                               obj.CAT_Semester.ID,
                               obj.CAT_Semester.SemesterName
                           };
            dic.Add(-1, "----Chọn Học Kì----");
            foreach (var item in Semester)
            {
                dic.Add(item.ID, item.SemesterName);

            }
            cbosemester1.Properties.ValueMember = "Key";
            cbosemester1.Properties.DisplayMember = "Value";
            cbosemester1.Properties.DataSource = dic;
            cbosemester1.EditValue = -1;

        }
        //load dataset
        private void LoadDataSet()
        {
            try
            {
                var query1 = from h in Model.PRI_StudentInSemester
                             select new
                             {
                                 h.StudentID,
                                 h.PRI_Student.Lastname,
                                 h.PRI_Student.Firstname,
                                 h.CAT_Class.Name,
                                 h.ClassID,
                                 h.CAT_Semester.SemesterName,
                                 year = h.CAT_Year.Name,
                                 h.TemplateID,
                                 h.StatusPrint,
                                 department = h.CAT_Department.Name,
                                 h.SchoolFee,
                                 h.TotalMoneyDebt,
                                 h.ID,
                                 h.SemesterAverage,
                                 h.SponsorBy,
                                 h.Address,
                                 h.SchoolFeeDebt,
                                 h.ResitFeeDebt
                             };
                var query2 = (from g in Model.PRI_SubjectSetting
                              select
                              new
                              {
                                  g.SubjectID,
                                  g.IsMain,
                                  g.TeacherID,
                                  Signature = (g.TeacherID == null) ? null : g.PRI_Teacher.Signature
                              }).ToList();

                _ds = new dsReport();

                foreach (var item1 in query1.Take(1))
                {
                    int i = 1;
                    int j = 1;
                    var query = from c in Model.PRI_StudentInSubject
                                where c.StudentID == item1.StudentID
                                select new
                                {
                                    c.SubjectID,
                                    c.PRI_Subjects.SubjectName,
                                    c.TotalScore,
                                    c.Remarks,
                                    c.PRI_Subjects.Code
                                 };
                    var d = Model.CAT_Class.FirstOrDefault(c => c.ID == item1.ClassID);
                    DataRow dt = _ds.Student.NewRow();
                    dt["Name"] = item1.Firstname + " " + item1.Lastname;
                    dt["Class"] = item1.Name;
                    dt["Year"] = item1.year;
                    dt["Semester"] = item1.SemesterName;
                    dt["Department"] = item1.department;
                    dt["SemesterAverage"] = item1.SemesterAverage;
                    dt["Sponsor"] = item1.SponsorBy;
                    dt["Address"] = item1.Address;
                    if (d.SectorID == null)
                    {
                        dt["Sector"] = "";
                    }
                    else
                    {
                        dt["Sector"] = d.CAT_Sector.Name;
                    }
                    dt["SchoolFee"] = item1.SchoolFee.ToString("###,###,##0");
                    dt["TotalMoneyDebt"] = item1.TotalMoneyDebt.ToString("###,###,##0");
                    dt["SchoolFeeDebt"] = item1.SchoolFeeDebt.ToString("###,###,##0");
                    dt["ResitFeeDebt"] = item1.ResitFeeDebt.ToString("###,###,##0");

                    int len = item1.SchoolFee.ToString().Length;

                    if (item1.SchoolFee.ToString() != "0.0000")
                    {
                        dt["ConvertNumtoString"] = "(" + Doisosangchu(item1.SchoolFee.ToString().Substring(0, len - 5)) + " đồng chẵn)";
                    }
                    else
                    {
                        dt["ConvertNumtoString"] = "";
                    }
                    foreach (var item2 in query)
                    {
                        var g = query2.FirstOrDefault(c => c.SubjectID == item2.SubjectID);
                        if (g != null && g.IsMain == true && i<=15)
                        {
                            dt["MainSubject" + i] = item2.SubjectName;
                            // dt["AMainScore" + i] = item2.AttendanceScore;
                            // dt["MMainScore" + i] = item2.MidtermScore;
                            //  dt["F1MainScore" + i] = item2.FinalExamScore1;
                            //   dt["F2MainScore" + i] = item2.FinalExcamScore2;
                            dt["TMainScore" + i] = item2.TotalScore;
                            dt["RemarksM" + i] = item2.Remarks;
                            if (g.Signature != null)
                                dt["SignatureM" + i] = g.Signature;
                            dt["SubjectCodeM" + i] = item2.Code;
                            i++;
                            
                        }
                        else
                        {
                            dt["SubSubject" + j] = item2.SubjectName;
                            //  dt["ASubScore" + j] = item2.AttendanceScore;
                            //   dt["MSubScore" + j] = item2.MidtermScore;
                            //   dt["F1SubScore" + j] = item2.FinalExamScore1;
                            //    dt["F2SubScore" + j] = item2.FinalExcamScore2;
                            dt["TSubScore" + j] = item2.TotalScore;
                            dt["RemarksS" + i] = item2.Remarks;
                            if (g.Signature != null)
                                dt["SignatureS" + i] = g.Signature;
                            dt["SubjectCodeS" + i] = item2.Code;
                              j++;
                            
                        }
                    }
                    _ds.Student.Rows.Add(dt);
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        static Hashtable hs = new Hashtable();
        static Hashtable h = new Hashtable();
        public static string Doisosangchu(string chuoi)
        {

            h["0"] = " nghìn ";
            h["1"] = " triệu ";
            h["2"] = " tỉ ";
            h["3"] = " nghìn tỉ ";
            h["4"] = " triệu tỉ ";
            h["5"] = " tỉ tỉ ";

            hs["0"] = "lẻ";
            hs["1"] = "một";
            hs["2"] = "hai";
            hs["3"] = "ba";
            hs["4"] = "bốn";
            hs["5"] = "năm";
            hs["6"] = "sáu";
            hs["7"] = "bảy";
            hs["8"] = "tám";
            hs["9"] = "chín";
            hs["10"] = "mười";
            hs["11"] = "mười một";
            hs["12"] = "mười hai";
            hs["13"] = "mười ba";
            hs["14"] = "mười bốn";
            hs["15"] = "mười lăm";
            hs["16"] = "mười sáu";
            hs["17"] = "mười bảy";
            hs["18"] = "mười tám";
            hs["19"] = "mười chín";
            hs["20"] = "hai mươi";
            hs["30"] = "ba mươi";
            hs["40"] = "bốn mươi";
            hs["50"] = "năm mươi";
            hs["60"] = "sáu mươi";
            hs["70"] = "bảy mươi";
            hs["80"] = "tám mươi";
            hs["90"] = "chín mươi";
            string returnkqua = "";

            string chuoicd;

            chuoicd = ThemDauPhayVaoChuoi(chuoi);

            int countdauphay = 0;
            foreach (char item in chuoicd)
            {
                if (item == ',')
                {
                    countdauphay++;
                }
            }

            string[] chuoiktra = chuoicd.Split(',');

            for (int i = 0; i < chuoiktra.Length; i++)
            {
                countdauphay = countdauphay - 1;
                returnkqua += KTText(chuoiktra[i]);
                if (chuoiktra[i] != "000")
                {
                    returnkqua += h[countdauphay.ToString()];
                }

            }
            return returnkqua;

        }

        public static string ThemDauPhayVaoChuoi(string chuoi)
        {
            string chuoicd;
            int sodu = chuoi.Length % 3;

            if (sodu != 0)
            {
                chuoicd = chuoi.Insert(sodu, ",");
                for (int i = 1; i < chuoi.Length / 3; i++)
                {
                    sodu += 4;
                    chuoicd = chuoicd.Insert(sodu, ",");
                }
            }
            else
            {
                sodu += 3;
                chuoicd = chuoi;
                for (int i = 1; i < chuoi.Length / 3; i++)
                {
                    chuoicd = chuoicd.Insert(sodu, ",");
                    sodu += 4;

                }
            }
            return chuoicd;
        }

        private static string KTText(string text)
        {
            string kqua = "";

            if (text == "000" || text == "00" || text == "0")
            {
                kqua = "";
            }
            else if (text.Length == 3)
            {
                int dv, c, tram;
                dv = int.Parse(text.Substring(text.Length - 1));
                c = int.Parse(text.Substring(1));
                int chuc = c - dv;
                tram = int.Parse(text.Substring(0, 1));

                if (dv == 0 && chuc != 0)
                    kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " ";
                else if (chuc == 0 && dv == 0)
                    kqua = hs[tram.ToString()] + " trăm ";
                else if (tram == 0 && chuc == 0)
                {
                    if (dv != 1)
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " một ";
                }
                else if (tram == 0)
                {
                    if (dv != 1)
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " mốt ";
                }
                else
                {
                    if (dv != 1)
                        kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " mốt ";
                }
            }
            else if (text.Length == 2)
            {
                int dv;
                dv = int.Parse(text.Substring(1));
                int chuc = int.Parse(text) - dv;
                if (dv == 0)
                    kqua = hs[chuc.ToString()].ToString() + " ";
                else
                {
                    if (dv != 1 || dv != 5)
                        kqua = hs[chuc.ToString()].ToString() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else if (dv == 1)
                        kqua = hs[chuc.ToString()].ToString() + " một ";
                    else if (dv == 5 && chuc == 0)
                        kqua = hs[chuc.ToString()].ToString() + " năm ";
                }
            }
            else if (text.Length == 1)
            {
                int dv;
                dv = int.Parse(text);
                if (dv != 5)
                    kqua = hs[dv.ToString()].ToString() + " ";
                else
                    kqua = "năm ";

            }
            return kqua;
        }
        private void LoadData()
        {
            int year = Convert.ToInt32(cboyear1.EditValue);
            int semester = Convert.ToInt32(cbosemester1.EditValue);
            var query = from c in Model.PRI_Template 
                     
                        where c.DepartmentID == DepartmentID && c.YearID==year && c.SemesterID==semester
                        select new
                        {
                            c.ID,
                            c.CAT_Year.Name,
                            c.CAT_Semester.SemesterName,
                           // c.DepartmentID,
                            c.TemplateName,
                           // c.IsPublic,
                            //c.Stream,
                            //c.HTML,
                            c.CreatedBy,
                            c.CreatedDate,
                            c.ModifiedBy,
                            c.ModifiedDate
                        };
            gvData.DataSource = query;
        }

        private void Edit()
        {
            object cellValue = gridView3.GetFocusedRowCellValue("ID");
            if (cellValue != null)
            {
                CheckAuth("Edit");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = Convert.ToInt32(cellValue);
                var obj = Model.PRI_Template.FirstOrDefault(c => c.ID == _id);
                if (obj != null)
                {
                    cboYear.EditValue = obj.YearID;
                    cboSemester.EditValue = obj.SemesterID;
                    txtTemp.EditValue = obj.TemplateName;
                    checkusededit();
                }

            }
        }

        private void gvData_DoubleClick(object sender, EventArgs e)
        {

            try
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
                Point pt = view.GridControl.PointToClient(Control.MousePosition);
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = view.CalcHitInfo(pt);
               // btnView.Enabled = true;
               // btnSave.Enabled = true;
                //checkusededit();
                if (info.InRow || info.InRowCell)
                {
                    Edit();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

       private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                object cellValue = gridView3.GetFocusedRowCellValue("ID");

                if (cellValue != null)
                {
                    int id = Convert.ToInt32(cellValue);
                    var obj = Model.PRI_Template.FirstOrDefault(c => c.ID == id);
                    int? year = obj.YearID;
                    int? semester = obj.SemesterID;
                    bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.SemesterID == semester && c.IsUsed == true).Count() > 0;
                    bool check1 = Model.PRI_StudentInSemester.Where(c => c.TemplateID == id).Count() == 0;
                    if (check)
                    {
                        if (check1)
                        {
                            if (CommonConfirm("Bạn muốn xóa mẫu thư này?", "XOA"))
                            {
                                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                                _id = -1;

                                if (obj != null)
                                {
                                    if (obj.Stream != null)
                                    {
                                        Model.DeleteObject(obj);
                                        Model.SaveChanges();
                                        CommonMessage("Xóa thành công");
                                        LoadData();
                                    }
                                    else
                                    {
                                        CommonMessage("Không thể xóa mẫu thư chưa có nội dung");
                                    }
                                }
                            }

                        }
                        else
                        {
                            CommonMessage("Mẫu thư đã sử dụng để in không thể xóa");
                        }
                    }
                    else
                    {
                        CommonMessage("Học kì đang khóa không thể xóa");
                    }
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                CheckAuth("Add");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = -1;
                txtTemp.Text = string.Empty;
                cboSemester.EditValue = -1;
                cboYear.EditValue = -1;
                btnView.Enabled = false;
               // btnSave.Enabled = false;
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmCopyTemplateUser frm = new FrmCopyTemplateUser();
            frm.Show();
            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            try
            {
                //RefreshModel();
                LoadData();
                txtTemp.Text = string.Empty;
                cboSemester.EditValue = -1;
                cboYear.EditValue = -1;

            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void FrmCreateTemplateUser_Load(object sender, EventArgs e)
        {
            stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
            _ds = new dsReport();
            LoadSchoolYear();
           // LoadSemester();
           //LoadData();
            LoadSchoolYear1();
            LoadDataSet();
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
              //  txtTemp.Text = string.Empty;
              //  cboSemester.EditValue = -1;
              //  cboYear.EditValue = -1;
               // btnView.Enabled = true;
               // btnSave.Enabled = true;
                //checkusededit();
                Edit();

            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void cboYear_EditValueChanged(object sender, EventArgs e)
        {
            LoadSemester();
            checkused();
        }

        private void cboyear1_EditValueChanged(object sender, EventArgs e)
        {
            LoadSemester1();
            LoadData();
        }

        private void cbosemester1_EditValueChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            object cellValue = gridView3.GetFocusedRowCellValue("ID");
            if (cellValue != null)
            {
                _id = Convert.ToInt32(cellValue);
                {
                    var obj = Model.PRI_Template.FirstOrDefault(c => c.ID == _id);
                    if (obj != null)
                    {
                        if (obj.Stream != null)
                        {
                            Template rp = new Template();
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(obj.Stream);
                            rp.LoadLayout(ms);
                            rp.DataSource = _ds;
                            DevExpress.XtraReports.UI.ReportPrintTool printTool = new DevExpress.XtraReports.UI.ReportPrintTool(rp);
                            CommandParams cmd = new CommandParams();
                            // cmd.IsPrint = false;
                            // printTool.PrintingSystem.AddCommandHandler(new PrintCommandHandler(cmd));
                            printTool.ShowPreviewDialog();
                        }

                    }
                    else
                    {
                        CommonMessage("Chưa chọn mẫu thư");
                    }
                }
            }
            else
            {
                CommonMessage("Chưa chọn mẫu thư");
            }
        }

        private void btnsavename_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckInput())
                {
                    var template = Model.PRI_Template.FirstOrDefault(c => c.ID == _id);
                    object obj = gridView3.GetFocusedRowCellValue("ID");
                    if (template != null)
                    {
                        int id = Convert.ToInt32(obj);

                        if (obj != null)
                        {
                            
                            template.ModifiedDate = DateTime.Now;
                            template.ModifiedBy = UserName;
                            template.TemplateName = txtTemp.EditValue.ToString();
                            template.IsPublic = false;
 
                        }
                    }
                    else
                    {

                        template = new Main_Data.PRI_Template();
                        template.ID = -1;
                        template.CreatedDate = DateTime.Now;
                        template.CreatedBy = UserName;
                        template.DepartmentID = DepartmentID;
                        template.TemplateName = txtTemp.EditValue.ToString();
                        FrmCreateTemplate frm = new FrmCreateTemplate();
                        frm.Data = _ds;
                        frm.TemplateStream = template.Stream;
                        frm.ShowDialog();
                        template.YearID = Convert.ToInt32(cboYear.EditValue);
                        template.SemesterID = Convert.ToInt32(cboSemester.EditValue);
                        template.IsPublic = false;
                        if (_id == -1)
                            Model.AddToPRI_Template(template);
                        if (frm.IsChanged)
                        {
                            template.Stream = frm.TemplateStream;

                        }

                    }
                    Model.SaveChanges();
                    LoadData();
                    txtTemp.Text = string.Empty;
                    cboSemester.EditValue = -1;
                    cboYear.EditValue = -1;
                    CommonMessage("Cập nhật thành công");
                }
            }


            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void checkused()
        {
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.SemesterID == semester && c.IsUsed == true).Count() > 0;
            if (check)
            {
                btnSave.Enabled = false;
                btnsavename.Enabled = true;
                btnView.Enabled = false;
            }
            else
            {
                btnSave.Enabled = false;
                btnsavename.Enabled = false;
                btnView.Enabled = false;
            }
        }
        private void checkusededit()
        {
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.SemesterID == semester && c.IsUsed == true).Count() > 0;
            if (check)
            {
                btnSave.Enabled = true;
                btnsavename.Enabled = true;
                cboSemester.Enabled = true;
                cboYear.Enabled = true;
                txtTemp.Enabled = true;
                btnView.Enabled = true;
            }
            else
            {
                btnSave.Enabled = false;
                btnsavename.Enabled = false;
                cboSemester.Enabled = false;
                cboYear.Enabled = false;
                txtTemp.Enabled = false;
                btnView.Enabled = true;

            }
        }
        private void cboSemester_EditValueChanged(object sender, EventArgs e)
        {
            checkused();
        }
       
       

       

        
     

        

      

        

       


        

        

      
    }
}
